# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

require_dependency RAILS_ROOT + '/vendor/plugins/annotations/lib/app/controllers/application_controller'

class ApplicationController < ActionController::Base
  before_filter :authorize, :except => [:login]
  
  layout "home"
  
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details
  
  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password
  
  rescue_from ActionController::RoutingError do |x|
    render :file => "public/404.html", :status => 404
  end
  
  def login_required
    respond_to do |format|
      format.html do
        if session[:user_id]
          @current_user = User.find(session[:user_id])
        else
          #session[:original_uri] = request.request_uri
          flash[:notice] = "Please log in"
          redirect_to new_session_url
        end
      end
      format.xml  do
        user = authenticate_with_http_basic do |login, password|
          User.authenticate(login, password)
        end
        if user
          @current_user = user
        else
          request_http_basic_authentication
        end
      end
    end
  end
  
  # Returns true or false if the user is logged in.
  def logged_in?
    return session[:user_id] ? true : false
  end
  helper_method :logged_in?
  
  # Accesses the current user from the session.
  def current_user
    @current_user ||= (session[:user_id] && User.find(session[:user_id])) || nil
  end
  helper_method :current_user
  
  # Returns true if user is admin
  def is_admin?
    return false unless logged_in?
    return current_user.access > 0 ? true : false
  end
  helper_method :is_admin?
  
  protected 
  
  def authorize    
    unless logged_in? # NOT LOGGED IN
      session[:original_uri] = request.request_uri
      flash[:notice] = "Please log in" 
      redirect_to :controller => "home", :action => "login"   
    else    
      unless is_admin?
        flash[:notice] = "You do not have suffiecient priviledges to view this area" 
        redirect_to :controller => "home"
      end
    end 
  end 
  
  private
  
  def rescue_from_errors
    flash[:notice] = "You have been redirected because an error occur while trying to process your request."
    redirect_to :back
  end
end